package com.up.upzl.biz.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.domain.SysApp.Type;
import com.up.upzl.biz.service.SysAppService;

/**
 * 系统用户控制器
 * 
 * @author geeks
 *
 */
@Controller
@RequestMapping("sysApp")
public class SysAppController {

	@Autowired
	private SysAppService sysAppService;

	@GetMapping("list")
	public String AppList(String AppName, Pageable page, Model model) {
		page = new PageRequest(page.getPageNumber(), page.getPageSize(), new Sort(Direction.DESC, "sort"));
		Page<SysApp> list = null;
		if (StringUtils.isEmpty(AppName)) {
			list = sysAppService.findAll(page);
		} else {
			list = sysAppService.findByCondition(AppName, page);
		}
		model.addAttribute("pageList", list);
		return "sysApp/list";
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("addPage")
	public String add(Model model) {
		Type[] typeEnum = Type.values();
		model.addAttribute("type", typeEnum);
		return "sysApp/add";
	}

	/**
	 * 保存对象
	 */
	@PostMapping("add")
	public @ResponseBody SysApp save(SysApp sysApp) {
		return sysAppService.save(sysApp);
	}

	/**
	 * 跳转到更新页面
	 */
	@GetMapping({ "updatePage", "detail" })
	public String update(Long id, Model model) {
		SysApp sysApp = sysAppService.findOne(id);
		model.addAttribute("entity", sysApp);
		Type[] typeEnum = Type.values();
		model.addAttribute("type", typeEnum);
		return "sysApp/update";
	}

	/**
	 * 更新
	 */
	@PostMapping("update")
	public @ResponseBody SysApp update(SysApp sysApp) {
		Assert.notNull(sysApp.getId(), "Id can`t be null");
		return sysAppService.save(sysApp);
	}

	/**
	 * 删除
	 */
	@PostMapping("delete")
	public @ResponseBody Map<String, String> delete(SysApp sysApp) {
		Assert.notNull(sysApp.getId(), "Id can`t be null");
		Map<String, String> map = new HashMap<>();
		try {
			sysAppService.delete(sysApp.getId());
		} catch (Exception e) {
			map.put("Type", "500");
			return map;
		}
		map.put("Type", "200");
		return map;
	}

}
